<?php
namespace Modules\Entity\Controllers;

use Core\Mvc\Controller;

class IndexController extends Controller
{
    public function indexAction($entity, $id)
    {
        $entityList = $this->config->cache('entity');
        $data = $this->entityManager->get($entity, $id);
        $entityInfo = $entityList[$entity];
        if (!isset($entityInfo['page']['node']) || $entityInfo['page']['node'] === false) {
            return $this->notFount();
        }
        if (!$data || $data->created > time()) {
            return $this->notFount();
        }
        self::$variables['data'] = $data;
        self::$variables['title'] = $data->getTitle();
        self::$variables['#templates'] = array(
            'pageEntity',
            'pageEntity' . ucfirst($entity),
            'pageEntity' . ucfirst($entity) . ucfirst($data->contentModel),
            'pageEntity' . ucfirst($entity) . $id,
        );
    }

    public function entityListAction($entity)
    {
        $contentModelInfo = $this->entityManager->contentModel($entity);
        $entityList = $this->config->cache('entity');
        $entityInfo = $entityList[$entity];
        if (!isset($entityInfo['page']['list']) || $entityInfo['page']['list'] === false) {
            return $this->notFount();
        }

        self::$variables += array(
            '#templates' => array(
                'pageEntityList',
                'pageEntityList-' . $entity,
            ),
            'contentModelInfo' => $contentModelInfo,
            'entity' => $entity,
        );
    }

    public function entityModelListAction($entity, $contentModel, $page)
    {
        $entity = $this->entityManager->get($entity);
        $entityList = $this->config->cache('entity');
        $entityInfo = $entityList[$entity];
        if (!isset($entityInfo['page']['contentModelList']) || $entityInfo['page']['contentModelList'] === false) {
            return $this->notFount();
        }
        $query = array(
            'andWhere' => array(
                array(
                    'conditions' => '%contentModel% = :contentModel:',
                    'bind' => array('contentModel' => $contentModel),
                ),
            ),
            'limit' => 15,
            'paginator' => true,
            'page' => $page,
        );
        $data = $this->entityManager->find($entity, $query);
        self::$variables += array(
            '#templates' => array(
                'pageEntityTypeList',
                'pageEntityTypeList-' . $entity,
                'pageEntityTypeList-' . $entity . '-' . $contentModel,
            ),
            'data' => $data,
            'entity' => $entity,
            'page' => $page,
        );
    }
}
